const db = require("../db/index");
const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");


//注册
exports.registUser = (req, res) => {
  const userinfo = req.body;
  if (userinfo.studentid.length < 5) {
    return res.send({
      code: 1001,
      message: "学号格式不合法",
    });
  }
  if (userinfo.username.length < 1) {
    return res.send({
      code: 1001,
      message: "昵称不合法",
    });
  }
  const sql = "select * from user where studentid = ?";
  db.query(sql, [userinfo.studentid], (err, result) => {
    if (err) {
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    }
    if (result.length > 0) {
      return res.send({
        code: 1002,
        message: "该学号已注册过,请直接登录",
      });
    }
    //调用bcryptjs的hashSync()对密码进行加密
    userinfo.password = bcrypt.hashSync(userinfo.password, 10);
    const insertsql = "insert into user set ?";
    db.query(insertsql, userinfo, (err, result) => {
      if (err) {
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      }
      if (result.affectedRows !== 1)
        return res.send({
          code: 1003,
          message: "注册失败，请稍后再试",
        });
      //注册成功
      res.send({
        code: 200,
        message: "注册成功",
      });
    });
  });
};
//登录
const Key = "kukiqwq55";
exports.login = (req, res) => {
  const userinfo = req.body;
  const sqlStr = "select * from user where studentid = ? and status = 1";
  //查询数据库
  db.query(sqlStr, userinfo.studentid, (err, result) => {
    if (err) {
      return res.send({
        code: 500,
        msg: "数据库异常" + err.message,
      });
    }
    //小于1说明没查到这个人
    if (result.length < 1)
      return res.send({
        code: 1001,
        message: "不存在此用户",
      });
    const compareresult = bcrypt.compareSync(
      userinfo.password,
      result[0].password
    );
    if (!compareresult) {
      return res.send({
        code: 1002,
        message: "密码错误",
      });
    }
    //生成token
    const tokenStr = jwt.sign(
      {
        id: result[0].id,
        username: result[0].username,
      },
      Key,
      {
        expiresIn: "24h",
      }
    );
    //把token发送给客户端
    res.send({
      code: 200,
      msg: "登陆成功",
      token: "Bearer " + tokenStr,
    });
  });
};

var fs = require("fs");
// 引入七牛模块
var qiniu = require("qiniu");
//要上传的空间名
var bucket = "kukiblog";
var imageUrl = "img.kukikuk.icu"; // 域名名称
var accessKey = "dXu5nJdraS7TZI3Uc4LXIH19edGtfuUWAQTO_0xH";
var secretKey = "sV4iULn8bCTPzHo7WoztzvPuUPWn0gsTvda_Gh5D";
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

var options = {
  scope: bucket,
  expires:7200
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);

var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1;


//上传图片
exports.uploadImg =  (req, res)=> {
  var imgData,type;
  if (req.body.type === "face") {
    imgData = req.body.image;
    type = req.body.imgType;
  } else {
    // 图片数据流
    imgData = req.body.image.miniurl;
    type = req.body.image.imgType;
  }
  // 构建图片名
  var fileName = Date.now() + "." + type;
  // 构建图片路径
  var filePath = "./public/img/" + fileName;
  //过滤data:URL
  var base64Data = imgData.replace(/^data:image\/(.*?);base64,/, "");
  var dataBuffer = Buffer.from(base64Data, "base64");
  fs.writeFile(filePath, dataBuffer, function (err) {
    if (err) {
      console.log(err);
      res.end(
        JSON.stringify({
          status: "102",
          msg: err,
        })
      );
    } else {
      var localFile = filePath;
      var formUploader = new qiniu.form_up.FormUploader(config);
      var putExtra = new qiniu.form_up.PutExtra();
      var key = fileName;

      // 文件上传
      formUploader.putFile(
        uploadToken,
        key,
        localFile,
        putExtra,
        function (respErr, respBody, respInfo) {
          if (respErr) {
            res.send(
              JSON.stringify({
                status: "-1",
                msg: "上传失败,请稍后重试",
                error: respErr,
              })
            );
            uploadToken = putPolicy.uploadToken(mac);
          }
          if (respInfo.statusCode == 200) {
            var imageSrc = imageUrl + `/` + respBody.key;
            res.send(
              JSON.stringify({
                status: "200",
                msg: "上传成功",
                imageUrl: imageSrc,
              })
            );
          } else {
            res.send(
              JSON.stringify({
                status: "-1",
                msg: "上传失败",
                error: JSON.stringify(respBody),
              })
            );
          }
          // 上传之后删除本地文件
          fs.unlinkSync(filePath);
          return;
        }
      );
    }
  });
}